
with open('example.text,' 'r', encoding='utf-8') as f:
    content = f.read()
    print(content)

with open('example.text','r',encoding='utf-8') as f:
    for line in f:
        print(line.strip())


with open('output.text','w', encoding='utf-8') as f:
    f.write("第一行内容\n")
    f.write("第二行内容\n")

lines = ["第三行\n","第四行\n"]
with open('output.text', 'a', encoding='utf-8') as f:
    f.write("这是追加的内容\n")




import csv


data = [
    ['姓名','年龄','城市'],
    ['张三',25,'北京'],
    ['李四',30,'上海']
]


with open('people.csv', 'w', encoding='utf-8', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(data)


with open('people.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)



import csv
data_dict = [
    {'name': '张三', 'age': 25, 'city': '北京' },
    {'name': '李四', 'age': 30, 'city': '上海'}
]

with open('people_dict.csv', 'w', encoding='utf-8', newline='') as f:
    fieldnames = ['name', 'age', 'city']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data_dict)

with open('people_dict.csv', 'r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['name']}居住在 {row['city']}")




import csv

def save_grades(filename,students):
    """将学生成绩保存为CSV"""
    with open(filename, 'w', encoding='utf-8',newline='') as f:
        writer = csv.DictWriter(f, fieldnames=['学号', '姓名', '成绩'])
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(students)


def load_grades(filename):
    """从CSV加载学生成绩"""
    with open (filename,'r', encoding='utf-8') as f:
        return list(csv.DictReader(f))




students = [
    {'学号': '1001', '姓名': '张三', '成绩': '85'},
    {'学号': '1002', '姓名': '李四', '成绩': '92'}
]


save_grades('grades.scv', students)
loaded_data = load_grades('grades.csv')
print(loaded_data)






